package com.example.service;

import com.example.entity.Order;
import com.example.mapper.OrderDao;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService{
    @Autowired
    private AccountFeign accountFeign;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private StorageFeign storage;
    @Override
    @GlobalTransactional(name = "order",rollbackFor = Exception.class)
    public Boolean createOrder(Order order) {
        log.info("创建订单");
        String XID = RootContext.getXID();
        System.out.println(XID);
        UUID uuid = UUID.randomUUID();
        ThreadLocalRandom current = ThreadLocalRandom.current();
        Long orderId= current.nextLong(6000000);
        order.setId(orderId);
        Boolean createOrder = orderDao.createOrder(order);
        if(!createOrder){
            throw new RuntimeException("创建订单错误");
        }
        log.info("修改库存");
        Boolean stroageRes = storage.modifiedStorage(order.getProductId(),order.getCount());
        if(!stroageRes){
            throw new RuntimeException("修改库存错误");
        }
        log.info("修改账户");
        Boolean accountRes = accountFeign.modifiedAccount(order.getUserId(), order.getMoney());
        if(!accountRes){
            throw new RuntimeException("修改账户错误");
        }
        log.info("修改订单状态");
        System.out.println(orderId+"=orderId");
        int i = this.modifiedStatus(orderId);
        if(i>=0){
            throw new RuntimeException("修改订单状态错误");
        }
        log.info("交易成功");
        return true;
    }

    @Override
    public int modifiedStatus(Long id) {
        int i = orderDao.modifiedStatus(id);
        return i;
    }
}
